<template>
  <div>
    <van-nav-bar title="登录" />
    <van-form ref='loginForm' @submit="longin">
      <van-field placeholder="请输入手机号"  v-model="user.mobile" type="number" :rules='fromrules.mobile'
      name="mobile"
      >
        <!-- 如果里面只有一个标签，可以省了template -->
        <i class="toutiao toutiao-shouji" slot='left-icon'></i>
      </van-field>

      <van-field placeholder="请输入验证码" v-model="user.code" type="number" :rules="fromrules.code">
        <!-- 常规插槽写法 -->
        <template #left-icon>
          <i class="toutiao toutiao-yanzhengma"></i>
        </template>
        <template #button>
            <van-count-down :time="time"  format="ss秒" v-if="!sending"  @finish='sending=!sending'/>
          <van-button size="small"  round  @click="sendCode" native-type="button" v-else>发送验证码</van-button>
        </template></van-field>

      <div class="box">
        <van-button block type="info" native-type="submit"
        :loading="loading"
          >登录</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import {sendSms , longin} from '@/api/user'
export default {
    data () {
        return {
            user : {
                mobile:'',
                code : ''
            },
            fromrules : {
                mobile : [{ required: true, message: '请填写手机号' },
                 { pattern: /^1\d{10}$/, message: '手机号码不正确' }
                ],
                code : [{ required: true, message: '请填写验证码' },
                { pattern: /^\d{4,6}$/, message: '请输入正确的验证码' }
                ]
            },
            sending:true ,
            time : 60000,
            loading:false
        }
    },
    methods: {
        //发送验证码
       async sendCode(){
           await this.$refs.loginForm.validate('mobile')
            await sendSms(this.user.mobile)
            this.$toast.success('验证码发送成功');
            this.sending=!this.sending
        },
        //登录板块
       async longin(){ 
         try {
            this.loading=true
            const res = await longin(this.user)
            //保存到本地
            // localStorage.setItem('token',res.data.token)
            this.$store.commit('user',res.data)
            this.$toast.success('马上给你跳转走');
            this.$router.push('/my')
         } finally{
            this.loading=false
         }
        }
    }
};
</script>

<style scoped>
 .box {
  margin: 16px;
}
</style>